package com.atguigu.tingshu.album.service.impl;

import cn.hutool.core.date.DateUtil;
import cn.hutool.core.io.file.FileNameUtil;
import cn.hutool.core.lang.UUID;
import cn.hutool.core.util.IdUtil;
import com.atguigu.tingshu.album.config.MinioConstantProperties;
import com.atguigu.tingshu.album.service.FileUploadService;
import com.atguigu.tingshu.common.execption.GuiguException;
import com.atguigu.tingshu.common.result.ResultCodeEnum;
import io.minio.MinioClient;
import io.minio.PutObjectArgs;
import io.minio.UploadObjectArgs;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import javax.imageio.ImageIO;
import java.awt.image.BufferedImage;
import java.io.IOException;

/**
 * @author: atguigu
 * @create: 2024-02-19 10:41
 */
@Slf4j
@Service
public class FileUploadServiceImpl implements FileUploadService {

    @Autowired
    private MinioClient minioClient;

    @Autowired
    private MinioConstantProperties props;


    /**
     * 图片文件上传接口；将图片上传到MInIO中返回图片在线地址
     *
     * @param file 上传文件
     * @return 在线地址
     */
    @Override
    public String fileUpload(MultipartFile file) {
        try {
            //1.上传文件是否为图片
            BufferedImage read = ImageIO.read(file.getInputStream());
            if (read == null) {
                throw new GuiguException(400, "图片文件有误！");
            }
            //2.调用MInIO客户端对象方法将图片上传到MInIO
            //2.1 生成随机的文件名称 避免同文件名不同文件被覆盖
            String today = DateUtil.today();
            String fileName = IdUtil.randomUUID();
            String extName = FileNameUtil.extName(file.getOriginalFilename());
            String objectName = "/" + today + "/" + fileName + "." + extName;
            //2.2 上传文件到MInIO
            minioClient.putObject(
                    PutObjectArgs.builder()
                            .bucket(props.getBucketName())
                            .object(objectName).stream(
                                    file.getInputStream(), file.getSize(), -1)
                            .contentType(file.getContentType())
                            .build());
            //3.拼接上传后文件在线地址
            return props.getEndpointUrl() + "/" + props.getBucketName() + objectName;
        } catch (Exception e) {
            log.error("[专辑服务]图片文件上传异常：{}", e);
            throw new GuiguException(400, "文件上传失败！");
        }
    }


}
